package com.koron.ui;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.AbstractAction;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

/**
 * 表格粘贴功能实现 处理了\t \n功能，可以从excel中直接把数据粘贴到table中
 * 
 * @author 方志文
 * 
 */
public class TableParseAction extends AbstractAction {
	public static final int EXTENDROW = 1;
	public static final int EXTENDCOLUMN = 2;
	/**
	 * 执行粘贴的表格
	 */
	private JTable table;
	/**
	 * 自动扩展方式。
	 * 
	 * @see #EXTENDROW
	 * @see #EXTENDCOLUMN
	 */
	private int autoExtend;

	/**
	 * 构造函数
	 * 扩展方式仅当表格 {@link JTable#getModel()}为{@link DefaultTableModel}时有效
	 * @param table
	 *            粘贴的表格
	 * @param autoExtend
	 *            数据超过表格时的自动扩展方式
	 * @see #EXTENDCOLUMN
	 * @see #EXTENDROW
	 */
	public TableParseAction(JTable table, int autoExtend) {
		this.table = table;
		this.autoExtend = autoExtend;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// 后面把剪切板内容值放这
		String data = "";
		Clipboard board = Toolkit.getDefaultToolkit().getSystemClipboard();
		Transferable trans = board.getContents(table);

		// 用来判断剪切板是否包括回车换行
		// boolean containTab = false;
		if (trans.isDataFlavorSupported(DataFlavor.stringFlavor)) {
			try {
				data = (String) trans.getTransferData(DataFlavor.stringFlavor);
			} catch (UnsupportedFlavorException e1) {
				e1.printStackTrace();
				return;
			} catch (IOException e1) {
				e1.printStackTrace();
				return;
			}
		}
		if (table.isEditing()) {
			table.getCellEditor().cancelCellEditing();
		}
		int x = table.getSelectedRow();
		int y1 = table.getSelectedColumn();
		x = (x == -1) ? 0 : x;
		y1 = (y1 == -1) ? 0 : y1;
		int y = y1;

		Pattern p = Pattern.compile("([^\\n\\t]*)([\\n\\t])?");
		Matcher m = p.matcher(data);
		while (m.find()) {
			TableModel model = table.getModel();
			if (model instanceof DefaultTableModel) {
				if (table.getRowCount() <= x && (autoExtend & EXTENDROW)!= 0) {
					((DefaultTableModel) model).setRowCount(x + 1);
				} else if (table.getColumnCount() <= y && (autoExtend & EXTENDCOLUMN)!= 0) {
					((DefaultTableModel) model).setColumnCount(y + 1);
				}
			}
			if (table.getRowCount() > x && table.getColumnCount() > y)
				table.setValueAt(m.group(1), x, y);
			if(m.group(2)!=null)
			if (m.group(2).equals("\t"))
				y++;
			else if (m.group(2).equals("\n")) {
				x++;
				y = y1;
			}
		}
	}
}
